// active-audit.js
const api = require('../../utils/api.js')
const permissionUtils = require('../../utils/permissions.js')
const pagePermission = require('../../utils/pagepermission.js')
Page({
  data: {
    reportId: '',
    reportInfo: null,
    productItemImages: [], // 按产品编号分组的图片
    generalImages: [], // 通用图片
    auditImages: [], // 审核图片
    auditData: {}, // 按产品编号的审核数据
    generalAuditStatus: 1, // 通用图片审核状态
    submitting: false
  },

  onLoad(options) {
    // 页面权限检查
    if (!pagePermission.requirePagePermission('pages/active-audit/active-audit')) {
      return
    }
    

    
    if (options.id) {
      this.setData({
        reportId: options.id
      })
      this.loadActiveReportDetail()
    }
  },

  // 加载主动报工详情
  loadActiveReportDetail() {
    api.getActiveReportDetail(this.data.reportId).then(res => {
      const reportInfo = res.data.activeReport
      const productItemImages = res.data.productItemImages || []
      const generalImages = res.data.generalImages || []
      const auditImages = res.data.auditImages || []
      
      // 初始化审核数据
      const auditData = {}
      productItemImages.forEach(item => {
        auditData[item.item_no] = {
          status: item.audit_status || 0,
          reason: item.audit_reason || ''
        }
      })
      
      this.setData({
        reportInfo: reportInfo,
        productItemImages: productItemImages,
        generalImages: generalImages,
        auditImages: auditImages,
        auditData: auditData
      })
    }).catch(err => {
      console.error('加载主动报工详情失败:', err)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    })
  },

  // 选择审核图片
  chooseImage() {
    const remaining = 9 - this.data.auditImages.length
    if (remaining <= 0) {
      wx.showToast({
        title: '最多只能上传9张图片',
        icon: 'none'
      })
      return
    }

    wx.chooseImage({
      count: remaining,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const newImages = this.data.auditImages.concat(res.tempFilePaths)
        this.setData({
          auditImages: newImages
        })
      }
    })
  },

  // 删除审核图片
  deleteImage(e) {
    const index = e.currentTarget.dataset.index
    const auditImages = this.data.auditImages
    auditImages.splice(index, 1)
    this.setData({
      auditImages: auditImages
    })
  },

  // 预览图片
  previewImage(e) {
    const url = e.currentTarget.dataset.url
    const urls = e.currentTarget.dataset.urls
    
    wx.previewImage({
      current: url,
      urls: urls
    })
  },

  // 设置产品编号审核状态
  setItemAuditStatus(e) {
    const itemNo = e.currentTarget.dataset.itemNo
    const status = parseInt(e.currentTarget.dataset.status)
    const auditData = this.data.auditData
    
    if (status === 2) {
      // 如果是拒绝，需要输入原因
      wx.showModal({
        title: '拒绝原因',
        editable: true,
        placeholderText: '请输入拒绝原因',
        success: (res) => {
          if (res.confirm) {
            auditData[itemNo] = {
              status: status,
              reason: res.content || ''
            }
            this.setData({ auditData: auditData })
          }
        }
      })
    } else {
      // 如果是通过，直接设置
      auditData[itemNo] = {
        status: status,
        reason: ''
      }
      this.setData({ auditData: auditData })
    }
  },

  // 设置通用图片审核状态
  setGeneralAuditStatus(e) {
    const status = parseInt(e.currentTarget.dataset.status)
    
    if (status === 2) {
      // 如果是拒绝，需要输入原因
      wx.showModal({
        title: '拒绝原因',
        editable: true,
        placeholderText: '请输入拒绝原因',
        success: (res) => {
          if (res.confirm) {
            this.setData({ 
              generalAuditStatus: status,
              generalAuditReason: res.content || ''
            })
          }
        }
      })
    } else {
      // 如果是通过，直接设置
      this.setData({ 
        generalAuditStatus: status,
        generalAuditReason: ''
      })
    }
  },

  // 审核报工
  auditReport(e) {
    const status = parseInt(e.currentTarget.dataset.status)
    
    if (status === 2) {
      // 如果是拒绝，需要输入原因
      wx.showModal({
        title: '拒绝原因',
        editable: true,
        placeholderText: '请输入拒绝原因',
        success: (res) => {
          if (res.confirm) {
            this.submitAudit(status, res.content)
          }
        }
      })
    } else {
      this.submitAudit(status, '')
    }
  },

  // 提交审核
  submitAudit(status, reason) {
    const data = {
      report_id: this.data.reportId,
      status: status,
      audit_reason: reason,
      audit_data: this.data.auditData,
      general_audit_status: this.data.generalAuditStatus
    }
    
    if (this.data.generalAuditReason) {
      data.general_audit_reason = this.data.generalAuditReason
    }
    
    this.doSubmitAudit(data)
  },

  // 执行审核提交
  doSubmitAudit(data) {
    this.setData({ submitting: true })
    
    // 如果有图片，先上传图片
    if (this.data.auditImages.length > 0) {
      this.uploadAuditImages(data)
    } else {
      this.submitAuditData(data)
    }
  },

  // 上传审核图片
  uploadAuditImages(data) {
    const images = this.data.auditImages
    const uploadPromises = []
    
    console.log('开始上传审核图片，图片数量:', images.length)
    console.log('report_id:', this.data.reportId)
    
    images.forEach((imagePath, index) => {
      const promise = new Promise((resolve, reject) => {
        console.log('上传第', index + 1, '张图片:', imagePath)
        
        // 获取管理员token
        const adminToken = wx.getStorageSync('adminToken')
        const headers = {}
        if (adminToken) {
          headers['Authorization'] = 'Bearer ' + adminToken
        }
        
        wx.uploadFile({
          url: globalData.baseUrl + '/uploadAuditImage',
          filePath: imagePath,
          name: 'audit_images',
          header: headers,
          formData: {
            report_id: this.data.reportId,
            report_type: 'active' // 指定为主动报工类型
          },
          success: (res) => {
            console.log('图片上传成功，响应:', res)
            const result = JSON.parse(res.data)
            if (result.code === 1) {
              resolve(result.data.url)
            } else {
              console.error('图片上传失败，错误信息:', result.msg)
              reject(result.msg)
            }
          },
          fail: (err) => {
            console.error('图片上传失败，错误:', err)
            reject('上传失败')
          }
        })
      })
      uploadPromises.push(promise)
    })
    
    Promise.all(uploadPromises).then((urls) => {
      data.audit_images = urls
      this.submitAuditData(data)
    }).catch((err) => {
      this.setData({ submitting: false })
      wx.showToast({
        title: '图片上传失败',
        icon: 'none'
      })
    })
  },

  // 提交审核数据
  submitAuditData(data) {
    api.auditActiveReport(data).then(res => {
      this.setData({ submitting: false })
      
      wx.showToast({
        title: '审核成功',
        icon: 'success'
      })
      
      // 返回上一页
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    }).catch(err => {
      this.setData({ submitting: false })
      console.error('审核失败:', err)
      wx.showToast({
        title: err.msg || '审核失败',
        icon: 'none'
      })
    })
  },

  // 格式化时间
  formatTime(timestamp) {
    const date = new Date(timestamp * 1000)
    const year = date.getFullYear()
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    const hour = date.getHours().toString().padStart(2, '0')
    const minute = date.getMinutes().toString().padStart(2, '0')
    return `${year}-${month}-${day} ${hour}:${minute}`
  },

  // 格式化产品编号，去掉前缀
  formatItemNo(itemNo) {
    if (!itemNo) return ''
    // 去掉前缀 "ORD2025072591AE49-3+F-扪皮-"
    const prefix = 'ORD2025072591AE49-3+F-扪皮-'
    if (itemNo.startsWith(prefix)) {
      return itemNo.substring(prefix.length)
    }
    return itemNo
  },

  // 权限检查方法
  hasPermission(module, action) {
    const app = getApp()
    const adminInfo = app.globalData.adminInfo
    if (!adminInfo) {
      return false
    }
    return permissionUtils.hasPermission(adminInfo.id, module, action);
  },

  // 显示权限拒绝提示
  showPermissionDenied(module, action) {
    wx.showToast({
      title: `您没有${module}模块的${action}权限`,
      icon: 'none'
    })
  }
}) 